<!-- 知识库页面  zxy-2022-12-20 -->
<script setup lang='ts' name="PhysicalKnowlege">
import {onBeforeMount, ref, reactive} from 'vue'
import { ElMessage, ElMessageBox, FormRules} from 'element-plus'

import {HeaderData, Operation as Oper, RowOperbuttons} from '@/components/dTable/dTable'
import {OperButton, SearchButton, SearchFromItem, SearchFromJustify} from '@/components/dTable/dHeader'
import {PageConfig, defaultPage, defaultPageSize, defaultPageSizes, defaultLayout} from '@/components/dTable/dFooter'

import {ColorTheme, ColorRed, DialogType, SeleteData} from '@/api/config'
import {
  getKnowlegeList, deleteKnowlege,
  KnowlegeFormInfor, SearchFormData,  KnowlegeInfor, TableOperation
} from '@/api/physicalExaminationManager/physicalKnowlege'

import operation from '@/components/dTable/components/operation.vue'
import pageContainer from '@/components/pageContainer.vue'
import dTablePromote from '@/components/dTable/dTablePromote.vue'
import addKnowlege from './addKnowlege.vue'

import {transfDicArrData, getObjectByKey} from '@/util/common'

// import router from '@/router/index'
import useStore from '@/store/common'
import { routerPush } from '@/util/router'
const {store} = useStore.setup()

//当前页面 表格数据 定义
const tableData = ref<Array<KnowlegeInfor & RowOperbuttons>>([])

//显示加载状态
const showLoading = ref(false)
//纳入异常统计选项
const isExceptionList:Array<SeleteData> = [{label:'是', value:true}, {label:'否', value:false}]

//表格头部数据定义
const tableHeaderData = ref<Array<HeaderData>>([
  {prop:'name', label:'规则名称', columnType:'text', align:'left', 'min-width':'100'},
  {prop:'groupingName', label:'组别', columnType:'text', align:'left', 'min-width':'100'},
  {prop:'remark', label:'规则描述', columnType:'text', align:'left', 'min-width':'100'},
  {prop:'isExceptionName', label:'纳入异常描述', columnType:'text', align:'left', 'min-width':'100'},
  {prop:'oper', label:'操作', columnType:'slot', align:'left', 'width':'110', fixed:'right'}
])

//搜索表单定义
const searchFromItems = ref<Array<SearchFromItem>>([
  {label:'规则名称', placeholder:'请输入规则名称', prop:'name', type:'input', enterSubmit:true},
  {label:'组别', placeholder:'请选择组别', prop:'grouping', type:'selete', changeSubmit:true, seleteData:[]},
  {label:'纳入异常统计', placeholder:'请选择是否纳入异常统计', prop:'isException', type:'selete', changeSubmit:true, seleteData:isExceptionList}
])
const searchFromRules = reactive<FormRules>({
  name:[
    {required:false, message:'长度应不超过50个字符', max:50, trigger: ['change', 'blur']}
  ]
})
const searchFromData = reactive<SearchFormData>({
  name:null, grouping:null, isException:null
})

//表头按钮
const operButtons = ref<Array<OperButton>>([
  {label:'新增', type:'noraml', iconConfig:{icon:'common-add', type:'custom'}, code:'add'}
])

//分页配置
const pageConfig = ref<PageConfig>({
  currentPage:defaultPage,
  pageSize:defaultPageSize,
  pageSizes:defaultPageSizes,
  total:0,
  disabled:false,
  layout:defaultLayout
})

//表单靠左还是靠右
const searchFromJustify = ref<SearchFromJustify>('flexStart')

//搜索按钮配置
const searchButtons = ref<Array<SearchButton>>([
  {type:'search'},
  {type:'clear'}
])

//操作按钮定义
const rowOperButtons:Array<Oper> = [
  {code:'edit', label:'编辑', iconConfig:{icon:'common-edit', type:'custom', color:ColorTheme, size:20}},
  {code:'manage', label:'配置', iconConfig:{icon:'common-maintain', type:'custom', color:ColorTheme, size:20}},
  {code:'delete', label:'删除', iconConfig:{icon:'common-delete', type:'custom', color:ColorRed, size:20}}
]

//后端数据拼接字段
const setTableData = (data:Array<KnowlegeInfor>) => {
  const dataArr:Array<KnowlegeInfor & RowOperbuttons> = []
  data.forEach((item) => {
    dataArr.push({...item, isExceptionName:item.isException === true ? '是' : '否', oper:rowOperButtons})
  })
  tableData.value = dataArr
}

//搜索数据
const searchData = (resetPage?:boolean) => {
  showLoading.value = true
  if (resetPage) pageConfig.value.currentPage = 1
  getKnowlegeList({...searchFromData, page:pageConfig.value.currentPage, limit:pageConfig.value.pageSize}).then((res) => {
    showLoading.value = false
    const {data} = res.data
    pageConfig.value.total = data.total === null ? 0 : data.total
    setTableData(data.records)
  }).catch((error) => {
    showLoading.value = false
    console.warn(error)
  })
}

//搜索事件
const onSubmit = () => {
  searchData(true)
}

//清除搜索栏数据事件
const clearForm = () => {
  searchData(true)
}

//清空搜索表单事件
const onFormClear = () => {
  clearForm()
  searchData(true)
}

//显示弹窗
const showDialog = ref(false)


//关闭窗口事件
const onClose = () => {
  showDialog.value = false
  searchData()
}


//弹窗类型
const dialogType = ref<DialogType>('add')

//基础知识库数据模板
const baseKnowlegeFromInfor = {name:'', grouping:'', remark:'', isException:true,  id:undefined  }

//编辑的知识库数据
const currKnowlegeFromData = ref<KnowlegeFormInfor>({...baseKnowlegeFromInfor})

//清除数据
const clearDialogData = () => {
  currKnowlegeFromData.value = {...baseKnowlegeFromInfor}
}

//操作按钮事件
const onOperation = (name:TableOperation) => {
  if (name === 'add') {
    clearDialogData()
    dialogType.value = 'add'
    showDialog.value = true
  }
}

//分页尺寸改变事件
const onSizeChange = () => {
  searchData(true)
}

//当前页改变事件
const onCurrentChange = () => {
  searchData()
}

//编辑体检知识库基础信息
const editKnowlegeInfor = (row:KnowlegeFormInfor) => {
  currKnowlegeFromData.value = {...row}
  dialogType.value = 'edit'
  showDialog.value = true
}

//配置体检知识库
const manageKnowlegeInfor = (row:KnowlegeFormInfor) => {
  routerPush('ManagePhysicalKnowlege', {id:row.id})
}

//体检知识库删除
const deleteKnowlegeInfor = (row:KnowlegeInfor) => {
  ElMessageBox.confirm(
    '是否确认删除此规则？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      return deleteKnowlege(row.id)
    }).then(() => {
      ElMessage.success('删除成功')
      searchData(true)
    }).catch((error) => {
      console.warn(error)
    })
}

//操作插槽事件（编辑，配置，删除）事件
const cellOperation = (name:string, row:KnowlegeInfor) => {
  if (name === 'edit') {
    editKnowlegeInfor(row)
  } else if (name === 'manage') {
    manageKnowlegeInfor(row)
  } else if (name === 'delete') {
    deleteKnowlegeInfor(row)
  }
}

//获取字典
const getDic = () => {
  store.getDicData('grouping').then((res) => {
    const item = getObjectByKey(searchFromItems.value, 'prop', 'grouping')
    if (item && item.type === 'selete') {
      item.seleteData = transfDicArrData(res)
    }
  })
}

//DOM即将挂载
onBeforeMount(() => {
  getDic()
  searchData()
})
</script>

<template>
  <page-container>
    <d-table-promote
      :label-width="100"
      :show-loading="showLoading"
      :oper-buttons="operButtons"
      :table-data="tableData"
      :table-header-data="tableHeaderData"
      :page-config="pageConfig"
      :search-form-data="searchFromData"
      :search-rules="searchFromRules"
      :search-form-items="searchFromItems"
      :search-from-justify="searchFromJustify"
      :search-buttons="searchButtons"
      @form-submit="onSubmit"
      @form-clear="onFormClear"
      @operation="onOperation"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
    >
      <template #oper="scope">
        <operation :row="scope.row" :col="scope.item" @opertion-click="cellOperation" />
      </template>
    </d-table-promote>
  </page-container>
  <add-knowlege
    v-if="showDialog"
    :show-dialog="showDialog"
    :dialog-type="dialogType"
    :item-group-form-data="currKnowlegeFromData"
    @close="onClose"
  />
</template>

<style scoped>
</style>